<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文章标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入文章标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="所属部门" prop="dept">
        <treeselect style="width: 240px" v-model="queryParams.dept" :options="deptOptions" :show-count="true" placeholder="请选择所属部门" clearable />
      </el-form-item>
      <el-form-item label="一级分类" prop="articleOneClass">
        <el-select v-model="queryParams.articleOneClass" placeholder="请选择一级分类" clearable @change="handleOneClassChange">
          <el-option
            v-for="menu in retirementMenuList"
            :key="menu.id"
            :label="menu.name"
            :value="menu.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类" prop="articleTwoClass">
        <el-select v-model="queryParams.articleTwoClass" placeholder="请选择二级分类" clearable>
          <el-option
            v-for="classTwo in retirementClassTwoList"
            :key="classTwo.id"
            :label="classTwo.name"
            :value="classTwo.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="文章类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择文章类型" clearable @change="handleQueryTypeChange">
          <el-option
            v-for="dict in dict.type.article_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="文章状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择文章状态" clearable>
          <el-option
            v-for="dict in dict.type.article_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>-->

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>



    <el-table ref="table" v-loading="loading" :data="retirementArticleReviewList" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
<!--      <el-table-column label="主键" align="center" prop="id" />-->
      <el-table-column label="文章标题" align="center" prop="title">
        <template slot-scope="scope">
          <div class="text-truncate" :title="scope.row.title" @click="showContentDialog('文章标题', scope.row.title)">
            {{ scope.row.title }}
          </div>
        </template>
      </el-table-column>>

<!--      <el-table-column label="文章内容富文本" align="center" prop="desc" />-->
      <el-table-column label="所属部门" align="center" prop="deptName" />
      <el-table-column label="所属一级分类" align="center" prop="articleOneClassName" />
      <el-table-column label="所属二级分类" align="center" prop="articleTwoClassName" />
      <el-table-column label="文章类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.article_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="文章封面图" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="是否置顶" align="center" prop="isTop" >
        <template slot-scope="scope">
          <span>{{ scope.row.isTop === '1' ? '是' : '否' }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="文号" align="center" prop="policyCode" />
      <el-table-column label="发文地址" align="center" prop="location" />
      <el-table-column label="发文机构" align="center" prop="source" />-->
      <!--   0草稿 1审核中 2驳回 3已发布    -->
      <el-table-column label="文章状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.article_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="发布时间" align="center" prop="date" />
      <el-table-column label="驳回原因" align="center" prop="reason" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
                     <el-button
             size="mini"
             type="text"
             icon="el-icon-edit"
             @click="handleReview(scope.row)"
             v-hasPermi="['retirement:retirementArticleReview:edit']"
           >审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handlePreview(scope.row)"
          >预览</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="handleUnpublish(scope.row)"
            v-if="scope.row.status === 3"
            v-hasPermi="['retirement:retirementArticleReview:edit']"
          >撤销发布</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 文章审核对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="审核结果" prop="status">
              <el-select v-model="form.status" placeholder="请选择审核结果" style="width: 100%">
                <el-option label="审核通过" :value="3"></el-option>
                <el-option label="审核驳回" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="form.status === 2">
          <el-col :span="24">
            <el-form-item label="驳回原因" prop="reason">
              <el-input
                v-model="form.reason"
                type="textarea"
                placeholder="请输入驳回原因"
                :rows="4"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 文章预览对话框 -->
    <el-dialog  :visible.sync="previewOpen" width="45%" append-to-body>
      <div class="article-preview">
        <div class="article-header">
          <h2 class="article-title">{{ previewData.title }}</h2>
          <div class="article-meta">
            <span class="meta-item">所属部门：{{ previewData.deptName }}</span>
            <span class="meta-item">一级分类：{{ previewData.articleOneClassName }}</span>
            <span class="meta-item">二级分类：{{ previewData.articleTwoClassName }}</span>
            <span class="meta-item">文章类型：{{ getDictLabel(dict.type.article_type, previewData.type) }}</span>
            <span class="meta-item">创建时间：{{ previewData.createTime }}</span>
          </div>
        </div>
<!--        <div class="article-cover" v-if="previewData.image">
          <image-preview :src="previewData.image" :width="300" :height="200"/>
        </div>-->
        <div class="article-content" v-html="previewData.desc"></div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 内容展示弹框 -->
    <el-dialog :title="contentDialog.title" :visible.sync="contentDialog.visible" width="60%" append-to-body>
      <div class="content-display">
        <pre>{{ contentDialog.content }}</pre>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="contentDialog.visible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRetirementArticleReview, getRetirementArticleReview, delRetirementArticleReview, addRetirementArticleReview, updateRetirementArticleReview, unpublish } from "@/api/retirement/retirementArticleReview"
import { listRetirementMenu } from "@/api/retirement/retirementMenu"
import { listRetirementClassTwo } from "@/api/retirement/retirementClassTwo"
import { deptTreeSelect } from "@/api/system/user"
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"

export default {
  name: "RetirementArticleReview",
  components: { Treeselect },
  dicts: ['article_type', 'article_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文章审核表格数据
      retirementArticleReviewList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示预览弹出层
      previewOpen: false,
      // 预览数据
      previewData: {},
      // 部门树选项
      deptOptions: [],
      // 一级分类列表数据
      retirementMenuList: [],
      // 二级分类列表数据（用于搜索）
      retirementClassTwoList: [],
      // 内容展示弹框
      contentDialog: {
        visible: false,
        title: '',
        content: ''
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        desc: null,
        dept: null,
        articleOneClass: null,
        articleTwoClass: null,
        type: null,
        policyCode: null,
        image: null,
        isTop: null,
        location: null,
        source: null,
        status: null,
        reason: null,
        date: null,
        isDel: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        status: [
          { required: true, message: "请选择审核结果", trigger: "change" }
        ],
        reason: [
          {
            validator: (rule, value, callback) => {
              if (this.form.status === 2 && (!value || value.trim() === '')) {
                callback(new Error('驳回时必须填写驳回原因'))
              } else {
                callback()
              }
            },
            trigger: "blur"
          }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getDeptTree()
    this.getRetirementMenuList()
    this.getRetirementClassTwoList()
  },
  methods: {
    /** 查询文章审核列表 */
    getList() {
      this.loading = true
      listRetirementArticleReview(this.queryParams).then(response => {
        this.retirementArticleReviewList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        desc: null,
        dept: null,
        articleOneClass: null,
        articleTwoClass: null,
        type: null,
        policyCode: null,
        image: null,
        isTop: null,
        location: null,
        source: null,
        status: null,
        reason: null,
        date: null,
        isDel: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      // 重置时重新获取所有二级分类
      this.getRetirementClassTwoList()
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 审核按钮操作 */
    handleReview(row) {
      this.reset()
      // 只保留文章ID，其他字段都重置为空
      this.form = {
        id: row.id,
        status: null,
        reason: null
      }
      this.open = true
      this.title = "文章审核"
    },


    /** 提交审核 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 如果是审核通过，清空驳回原因
          if (this.form.status === 3) {
            this.form.reason = null
          }
          // 如果是驳回，确保有驳回原因
          if (this.form.status === 2 && (!this.form.reason || this.form.reason.trim() === '')) {
            this.$modal.msgError("驳回时必须填写驳回原因")
            return
          }

          updateRetirementArticleReview(this.form).then(response => {
            this.$modal.msgSuccess("审核完成")
            this.open = false
            this.getList()
          })
        }
      })
    },

    /** 预览按钮操作 */
    handlePreview(row) {
      this.previewData = { ...row }
      this.previewOpen = true
    },


    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
      })
    },

    /** 获取一级分类列表 */
    getRetirementMenuList() {
      listRetirementMenu({}).then(response => {
        this.retirementMenuList = response.data || []
      })
    },

    /** 获取二级分类列表（用于搜索） */
    getRetirementClassTwoList() {
      listRetirementClassTwo({}).then(response => {
        this.retirementClassTwoList = response.data || []
      })
    },

    /** 根据一级分类ID获取二级分类列表（用于搜索） */
    getQueryClassTwoList(levelOneId) {
      if (!levelOneId) {
        this.retirementClassTwoList = []
        return
      }
      listRetirementClassTwo({ levelOneId: levelOneId }).then(response => {
        this.retirementClassTwoList = response.data || []
      })
    },

    /** 搜索表单一级分类变化处理 */
    handleOneClassChange(value) {
      // 清空二级分类选择
      this.queryParams.articleTwoClass = null
      // 根据一级分类ID获取对应的二级分类
      this.getQueryClassTwoList(value)
    },
    /** 搜索表单文章类型变化处理 */
    handleQueryTypeChange(value) {
      // 这里可以添加搜索表单文章类型变化的逻辑
      console.log('搜索表单文章类型变化:', value)
    },

    /** 获取字典标签 */
    getDictLabel(dictOptions, value) {
      if (!dictOptions || !value) return ''
      const option = dictOptions.find(item => item.value === value)
      return option ? option.label : ''
    },

    /** 撤销发布按钮操作 */
    handleUnpublish(row) {
      this.$modal.confirm('确认撤销发布吗?').then(() => {
        return unpublish({ id: row.id })
      }).then(() => {
        this.$modal.msgSuccess("撤销发布成功")
        this.getList()
      }).catch(() => {})
    },
    // 显示内容弹框
    showContentDialog(title, content) {
      this.contentDialog.title = title
      this.contentDialog.content = content
      this.contentDialog.visible = true
    },
  }
}
</script>

<style scoped>
.article-preview {
  max-height: 70vh;
  overflow-y: auto;
}

.article-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e6e6e6;
}

.article-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 0 0 15px 0;
  line-height: 1.4;
}

.article-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  font-size: 14px;
  color: #666;
}

.meta-item {
  white-space: nowrap;
}

.article-cover {
  text-align: center;
  margin: 20px 0;
}

.article-content {
  margin-top: 20px;
  line-height: 1.8;
  font-size: 16px;
  color: #333;
}

.article-content >>> img {
  max-width: 100%;
  height: auto;
  margin: 10px 0;
}

.article-content >>> p {
  margin: 10px 0;
}

.article-content >>> h1,
.article-content >>> h2,
.article-content >>> h3,
.article-content >>> h4,
.article-content >>> h5,
.article-content >>> h6 {
  margin: 20px 0 10px 0;
  font-weight: bold;
}

.article-content >>> ul,
.article-content >>> ol {
  margin: 10px 0;
  padding-left: 30px;
}

.article-content >>> blockquote {
  margin: 15px 0;
  padding: 10px 15px;
  background-color: #f5f5f5;
  border-left: 4px solid #409eff;
}

.text-truncate {
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
  color: #409EFF;
}

.text-truncate:hover {
  color: #66b1ff;
}

.content-display {
  max-height: 500px;
  overflow-y: auto;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.content-display pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
  font-family: inherit;
  line-height: 1.5;
}
</style>
